package com.baidu.fengchao.broad.action;

import com.baidu.fengchao.broad.bo.Iface;
import com.baidu.fengchao.broad.bo.ProductType;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: xiaojiangang
 * Date: 13-5-2
 * Time: 下午11:27
 */
@IocBean
public class Api {
    private Dao dao;

    @At("/apis")
    @Ok("ioc:freemarker")
    @Fail("json")
    public Object apis(int apid) {
        if (apid > 0)
            return dao.fetch(Iface.class, apid);
        else return null;
    }

    @At({"/index","/lapi"})
    @Ok("ioc:freemarker")
    @Fail("json")
    public Object index() {
        List<ProductType> productTypeList = dao.query(ProductType.class, null);
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String, Object>> plist = new LinkedList<Map<String, Object>>();
        for (ProductType productType : productTypeList) {
            Map<String, Object> productInfo = new HashMap<String, Object>();
            productInfo.put("id", productType.getId());
            productInfo.put("name", productType.getName());
            productInfo.put("apis", dao.query(Iface.class, Cnd.where("productid", "=", productType.getId())));
            plist.add(productInfo);
        }
        result.put("plist", plist);
        return result;
    }

    @At("/product/new")
    @Ok("json")
    @Fail("json")
    public void newProduct(String name){
        ProductType productType = new ProductType();
        productType.setName(name);
        dao.insert(productType);
    }

    @At("/product/del")
    @Ok("raw")
    @Fail("json")
    public void newProduct(int id){
        Sql sql = Sqls.create("Delete from iface where productid="+id);
        dao.execute(sql);
        dao.delete(ProductType.class,id);
    }

    @At("/api/new")
    @Ok("raw")
    @Fail("json")
    public Object newApi(String title,String resp,String detail,int productid){
        Iface iface = new Iface();
        iface.setProductid(productid);
        iface.setTitle(title);
        iface.setResp(resp);
        iface.setDetail(detail);
        dao.insert(iface);
        return iface.getId();
    }
    @At("/api/del")
    @Ok("raw")
    @Fail("json")
    public void newApi(int id){
        dao.delete(Iface.class,id);
    }
    public void setDao(Dao dao) {
        this.dao = dao;
    }


}
